/*
 * $Id: GraphPanel.java,v 1.14 2003/06/29 11:16:19 znamenacek Exp $
 *
 * Copyright (c) Tomas Znamenacek
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

package net.sf.vofce.gui;

import net.sf.vofce.canvas.Axis;
import net.sf.vofce.canvas.AxisLabelLayer;
import net.sf.vofce.canvas.BoundingLayer;
import net.sf.vofce.canvas.DottedFunctionLayer;
import net.sf.vofce.canvas.GridLayer;
import net.sf.vofce.canvas.GuidelineLayer;
import net.sf.vofce.canvas.Layer;
import net.sf.vofce.canvas.LineFunctionLayer;
import net.sf.vofce.canvas.ReverseAxis;
import net.sf.vofce.canvas.RulersLayer;
import net.sf.vofce.canvas.TrivialLayer;
import net.sf.vofce.project.Config;
import net.sf.vofce.project.Project;
import net.sf.vofce.project.ProjectEventListener;
import net.sf.vofce.util.NiceProperties;
import net.sf.vofce.util.PropertyChangeListener;

import javax.swing.AbstractAction;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

import java.awt.Cursor;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;

/**
 * Panel that all the graphs and drawing appears on.
 *
 * @author Tomas Znamenacek
 */
public class GraphPanel extends JPanel implements
	PropertyChangeListener, ProjectEventListener,
	MouseListener, MouseMotionListener {

	public static final int MOUSEMODE_POINTER = 0;
	public static final int MOUSEMODE_ZOOM = 1;
	public static final int MOUSEMODE_MOVE = 2;
	
	/**
	 * Buffer that holds all the drawing.
	 * We use this buffer for double buffering to avoid recalculating
	 * things when possible.
	 */
	protected BufferedImage buffer;
	
	/**
	 * Dirty flag used for double buffering.
	 * If this flag is set to <code>false</code>, the viewport uses
	 * previously filled internal buffer to paint itself.
	 */
	protected boolean dirty = false;
	
	/** X axis. */
	protected Axis axisX;

	/** Y axis.  */
	protected Axis axisY;

	/**
	 * What to do in case we receive mouse click.
	 * Can be one of these constants:
	 * <ul>
	 * 	<li><code>MOUSEMODE_POINTER</code>&mdash;do nothing</li>
	 * 	<li><code>MOUSEMODE_ZOOM</code>&mdash;use mouse events to do zooming</li>
	 * 	<li><code>MOUSEMODE_MOVE</code>&mdash;use mouse events to move viewport</li>
	 * </ul>
	 */
	protected int mouseMode = MOUSEMODE_POINTER;

	/** Last point the mouse was seen at, used for dragging. */
	private Point lastPoint;

	private double tresholdX;
	private double tresholdY;

	public static final Layer LAYER_DOTTED = new DottedFunctionLayer();
	public static final Layer LAYER_LINED = new LineFunctionLayer();
	
	/** The layer used for painting the graphs. */
	protected Layer usedFunctionLayer = LAYER_LINED;
	
	/** Layers painted on the surface. */
	protected Layer[] layers = {
		new BoundingLayer(),
		new TrivialLayer(),
		new GridLayer(),
		new GuidelineLayer(),
		new AxisLabelLayer(),
		new RulersLayer(),
		usedFunctionLayer
	};

	/** <code>GraphPanel</code> instance. */
	protected static GraphPanel instance = new GraphPanel();

	/** Returns <code>GraphPanel</code> instance. */
	public static GraphPanel getInstance() {

		return instance;
	}
	
	/**
	 * Creates new graphed panel.
	 */
	private GraphPanel() {

		super();

		axisX = new Axis(10);
		axisY = new ReverseAxis(10);
		
		for (int i = 0; i < layers.length; i++) {

			layers[i].setAxis(axisX, axisY);
		}

		Config.getInstance().addChangeListener(this);
		Project.getInstance().addEventListener(this);
		addMouseListener(this);
		addMouseMotionListener(this);
	}

	/** Sets the graphing mode. */
	public void setGraphingMode(Layer graphingLayer) {

		graphingLayer.setAxis(axisX, axisY);
		layers[layers.length - 1] = graphingLayer;
		forceRepaint();
	}

	/** Returns the layers --- the axis, graphs etc. */
	public Layer[] getLayers() {

		return layers;
	}

	/** Forces the component to repaint itself. */
	public void forceRepaint() {
		
		dirty = true;
		repaint();
	}
	
	/**
	 * Triggered by configuration system when some configuration
	 * property changes.
	 */
	public void propertyChanged(String key) {

		forceRepaint();
	}

	/**
	 * Triggered by the project when the function set changes.
	 */
	public void functionSetChanged() {

		forceRepaint();
	}

	public void savingProject(NiceProperties props) {

		props.setInt("axis.x.position", axisX.getPosition());
		props.setDouble("axis.x.scale", axisX.getScale());
		
		props.setInt("axis.y.position", axisY.getPosition());
		props.setDouble("axis.y.scale", axisY.getScale());
	}
	
	public void projectLoaded(NiceProperties props) {

		axisX.set(props.getInt("axis.x.position", Axis.DEFAULT_POSITION),
			props.getDouble("axis.x.scale", Axis.DEFAULT_SCALE));
		
		axisY.set(props.getInt("axis.y.position", Axis.DEFAULT_POSITION),
			props.getDouble("axis.y.scale", Axis.DEFAULT_SCALE));

		forceRepaint();
	}

	public void projectCleared() {
	
		reset();
	}
	
	/** Component resize. */
	public void setBounds(int x, int y, int width, int height) {

		super.setBounds(x, y, width, height);

		if ((width != 0) && (height != 0)) {
			buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		}

		axisX.setPhysicalLength(width);
		axisY.setPhysicalLength(height);
		
		for (int i = 0; i < layers.length; i++) {

			layers[i].setAxis(axisX, axisY);
		}
	
		dirty = true;
	}

	/** Repaint the component, viewport and all the layers. */
	public void paint(Graphics g) {

		super.paint(g);
		
		if (dirty) {
			
			Graphics2D surface = buffer.createGraphics();
			
			for (int i = 0; i < layers.length; i++) {

				layers[i].render(surface);
			}

			dirty = false;
		}

		((Graphics2D) g).drawImage(buffer, 0, 0, null);
	}

	//
	// Axis manipulation
	// 
	
	public Axis axisX() {

		return axisX;
	}

	public Axis axisY() {

		return axisY;
	}
	
	//
	// Mouse listening
	//

	public void mouseEntered(MouseEvent e) {

		switch (mouseMode) {

			case MOUSEMODE_POINTER:
				break;
			
			case MOUSEMODE_ZOOM:
				setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
				break;
		}
	}
	
	public void mouseExited(MouseEvent e) {
		
		setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
	}
	
	public void mouseReleased(MouseEvent e) {
	
		switch (mouseMode) {

			case MOUSEMODE_POINTER:
				break;

			case MOUSEMODE_ZOOM:

				double x = axisX.physicalToLogical(e.getX());
				double y = axisY.physicalToLogical(e.getY());
		
				if (SwingUtilities.isLeftMouseButton(e)) {
					zoomIn();
				} else if (SwingUtilities.isRightMouseButton(e)) {
					zoomOut();
				}

				moveTo(x, y);
				break;

			case MOUSEMODE_MOVE:

				setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
				break;
		}
	}

	public void mousePressed(MouseEvent e) {
		
		switch (mouseMode) {

			case MOUSEMODE_MOVE:
				
				lastPoint = e.getPoint();
				setCursor(new Cursor(Cursor.MOVE_CURSOR));

				tresholdX = getWidth() / axisX.getMarks().length;
				tresholdY = getHeight() / axisY.getMarks().length;
				
				break;
		}
	}

	public void mouseClicked(MouseEvent e) {}
	
	/** Sets mouse behaviour. */
	public void setMouseMode(int mouseMode) {

		this.mouseMode = mouseMode;
	}

	//
	// Mouse movement listening
	//

	/**
	 * Respond to mouse drag.
	 */
	public void mouseDragged(MouseEvent e) {

		if (mouseMode != MOUSEMODE_MOVE) { return; }
		
		int deltaX = trunc((lastPoint.getX() - e.getX()) / tresholdX);
		int deltaY = trunc((lastPoint.getY() - e.getY()) / tresholdY);
	
		switch (mouseMode) {

			case MOUSEMODE_MOVE:
				
				if (deltaX != 0) {
					moveX(deltaX);
					lastPoint.setLocation(e.getX(), lastPoint.getY());
				}

				if (deltaY != 0) {
					moveY(-deltaY);
					lastPoint.setLocation(lastPoint.getX(), e.getY());
				}
				break;
		}

	}
	
	public void mouseMoved(MouseEvent e) {}
	
	private int trunc(double a) {

		return (int) ((a > 0) ? Math.floor(a) : Math.ceil(a));
	}
	
	//
	// Viewport manipulation
	// 
	
	/**
	 * Resets both axis to default values.
	 */
	public void reset() {

		axisX.reset();
		axisY.reset();
		forceRepaint();
	}

	/**
	 * Zooms in on both axis.
	 */
	public void zoomIn() {

		axisX.zoomIn();
		axisY.zoomIn();
		forceRepaint();
	}

	/**
	 * Zooms out on both axis.
	 */
	public void zoomOut() {

		axisX.zoomOut();
		axisY.zoomOut();
		forceRepaint();
	}

	/** Move the axis <code>x</code> by <code>shift</code> marks. */
	public void moveX(int shift) {

		axisX.move(shift);
		forceRepaint();
	}
	
	/** Move the axis <code>y</code> by <code>shift</code> marks. */
	public void moveY(int shift) {

		axisY.move(shift);
		forceRepaint();
	}

	/** Center the viewport on given point. */
	public void moveTo(double x, double y) {

		axisX.moveTo(x);
		axisY.moveTo(y);
		forceRepaint();
	}
}
